import { Component, OnInit,Input,Output,EventEmitter } from '@angular/core';
import { Bus } from '../bus';

import { ActivatedRoute, Params } from '@angular/router';
import { BusService } from '../bus.service';
import { CarrierService } from '../../carrier/carrier.service';
import { Carrier } from '../../carrier/carrier';

@Component({
    selector: 'bus-detail',
    templateUrl: './bus-detail.component.html',
    // styleUrls: ['./bus-detail.component.css']
})

export class BusDetailComponent implements OnInit {
    @Input()
    bus: Bus;

    @Output() onVoted = new EventEmitter();

    
    message : String;
    carriers: Carrier[];

    constructor(
        private busService: BusService,
        private carrierService: CarrierService,
        private router: ActivatedRoute) {

    }

    ngOnInit() {
        this.router.params.forEach((params: Params) => {
            let bus_id = +params['bus_id'];
            this.busService.getBus(bus_id).then(bus => this.bus = bus);
            this.carrierService.getCarriers().then(carriers => this.carriers = carriers);
        });
    }

    goBack() {
        window.history.back();
    }

    save(): void {
        this.busService.getMessage(this.bus)
        .then(buscheck => this.check(buscheck) ) ;
        // this.busService.save(this.bus).then(rexs => this.afterSave(rexs));
    }
    check(bus){
        if(bus.bus_id > 0){
            //this.message = "保存成功";
            this.cancel();
        }else{
            this.message = bus.plate_number;
        }

    }

    afterSave(rexs:string) {
        console.log(rexs);
        this.cancel();
    }

    delete(): void {
        this.busService.delete(this.bus).then(() => this.cancel());
    }

    cancel(): void {
        this.bus = null;
        this.onVoted.emit();
    }

}